#include <QCoreApplication>
#include <Ice/Ice.h>
#include <thread>
#include "tmglobaldef.h"

class Server : public Ice::Application
{
public:
    Server(QCoreApplication* p){
        m_pApp = p;
    }
    virtual int run(int argc, char* argv[]){
        // Init
        g_strRootDir = QCoreApplication::applicationDirPath();
        QDir::setCurrent(g_strRootDir);
        // 更新了全局RobotType和Version
        g_pSettingCore = new QSettings("./Config/Robot.ini", QSettings::IniFormat);
        g_pSettingCore->setIniCodec("UTF-8");
        g_pCodecASCII = QTextCodec::codecForName("GB18030");
        g_strRobotType = g_pSettingCore->value("Core/Type").toString();
        g_strCoreVersion = g_pSettingCore->value("Core/Version").toString();
        g_strAsrKeyCN = g_pSettingCore->value("ASR/AnsKeyCN").toString();
        g_strAsrKeyEN = g_pSettingCore->value("ASR/AnsKeyEN").toString();;
        g_strAudioCOM = g_pSettingCore->value("MicMatrix/COM").toString();
        g_bMicEnable = g_pSettingCore->value("MicMatrix/Enable").toBool();

        Ice::PropertiesPtr proptr = communicator()->getProperties();
        qDebug()<<"----Ice.MessageSizeMax:----"<<proptr->getProperty("Ice.MessageSizeMax").c_str();
        // Ice object
        Ice::ObjectAdapterPtr adapter = communicator()->createObjectAdapter("Robot");

        // Motor
        RobotMotorI* pMotorI = new RobotMotorI();
        adapter->add(pMotorI, communicator()->stringToIdentity("Motor"));
        // Json
        RobotJsonI* pJsonI = new RobotJsonI();
        adapter->add(pJsonI, communicator()->stringToIdentity("Json"));
        // Audio
        RobotAudioI* pAudioI = new RobotAudioI();
        pAudioI->Init();
        adapter->add(pAudioI, communicator()->stringToIdentity("Audio"));
        // Config
        RobotConfigI* pConfigI = new RobotConfigI();
        adapter->add(pConfigI, communicator()->stringToIdentity("Config"));

        // Pub
        RobotPubI* pPubI = new RobotPubI();
        adapter->add(pPubI, communicator()->stringToIdentity("Pub"));

        // FileMgr
        RobotFileMgrI* pFileMgrI = new RobotFileMgrI();
        adapter->add(pFileMgrI, communicator()->stringToIdentity("FileMgr"));

        adapter->activate();

        communicator()->waitForShutdown();
        g_pAudioSender->setExit();
        g_pSerialTh->setExit();
        g_pJsonEngTh->setExit();

        QCoreApplication::processEvents();
//        m_pApp->quit();
        m_pApp->exit();
        return 0;
    }
private:
    QCoreApplication* m_pApp;

};

void t_run(QCoreApplication* p){
    Server app(p);
    app.main(__argc, __argv);
}

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    std::thread t1(t_run, &a);
    t1.detach();
    return a.exec();
}
